﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml;
using System.Collections.Specialized;
using System.Deployment.Application;
using Gapi.Language;
using log4net;
using System.Diagnostics;

namespace WowTourGuideTranslator
{
    /// <summary>
    /// TourGuide Übersetzern Klasse
    /// </summary>
    public partial class TourGuideBaseTranslatorForm : Form
    {
        #region fields

        /// <summary>
        /// Context menu for translation lookups
        /// </summary>
        private ContextMenu contextMenuLookups = new ContextMenu();

        /// <summary>
        /// <c>true</c> if there are pending changes in the Untranslated grid
        /// </summary>
        private bool dataGridViewUntranslatedDirty = false;

        static private ILog log = LogManager.GetLogger(typeof(TourGuideBaseTranslatorForm));

        #endregion fields

        /// <summary>
        /// Initializes a new instance of the <see cref="TourGuideBaseTranslatorForm"/> class.
        /// </summary>
        public TourGuideBaseTranslatorForm()
        {

            if (!Program.RunsOnMono)
            {
                InitializeComponent();
            }
            else
            {
                InitializeComponentForMono();
            }
            DataProvider.Initialize(this, this.backgroundWorker);

            // fill language box
            this.comboBoxTargetLanguage.Items.Add(Language.German);
            this.comboBoxTargetLanguage.Items.Add(Language.French);
            this.comboBoxTargetLanguage.Items.Add(Language.Russian);
            this.comboBoxTargetLanguage.Items.Add(Language.Spanish);
            this.comboBoxTargetLanguage.SelectedIndex = 0;

            // init context menu
            StringCollection searchSitePairs = Properties.Settings.Default.SearchSitePairs;
            for (int lookupSettingIndex = 0; lookupSettingIndex < searchSitePairs.Count; lookupSettingIndex++)
            {
                string[] data = searchSitePairs[lookupSettingIndex].Split(';');

                if (data.Length != 2)
                {
                    continue;
                }

                // Search prefix
                string searchPrefix = @"Search at ";
                // item for edit box
                MenuItem item = new MenuItem(searchPrefix + data[0]);
                // item for grid
                ToolStripMenuItem stripItem = new ToolStripMenuItem(searchPrefix + data[0]);
                // set shortcut for the first 10 items
                if (lookupSettingIndex <= 9)
                {
                    item.Shortcut = (Shortcut)Enum.Parse(typeof(Shortcut), string.Format("Ctrl{0}", (lookupSettingIndex + 1) % 10));
                    item.ShowShortcut = true;
                    stripItem.ShortcutKeys = Keys.Control | (Keys)(Shortcut)Enum.Parse(typeof(Keys), string.Format("D{0}", (lookupSettingIndex + 1) % 10));
                    stripItem.ShowShortcutKeys = true;
                }
                // attach search url
                item.Tag = data[1];
                stripItem.Tag = data[1];

                // register handler
                item.Click += new EventHandler(contextMenuLookupsItem_Click);
                stripItem.Click += new EventHandler(contextMenuLookupsItem_Click);

                this.contextMenuLookups.MenuItems.Add(item);
                this.contextMenuStripLookup.Items.Add(stripItem);
            }

            this.dataGridViewUntranslated.ContextMenu = this.contextMenuLookups;
        }

        /// <summary>
        /// Initializes the component for mono (without Browser tab).
        /// </summary>
        private void InitializeComponentForMono()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TourGuideBaseTranslatorForm));
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
            this.buttonRun = new System.Windows.Forms.Button();
            this.progressBar = new System.Windows.Forms.ProgressBar();
            this.buttonBrowse = new System.Windows.Forms.Button();
            this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.comboBoxTargetLanguage = new System.Windows.Forms.ComboBox();
            this.labelTargetLanguage = new System.Windows.Forms.Label();
            this.backgroundWorker = new System.ComponentModel.BackgroundWorker();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.richTextBoxTrace = new System.Windows.Forms.RichTextBox();
            this.tabControl = new System.Windows.Forms.TabControl();
            this.tabPageFullLog = new System.Windows.Forms.TabPage();
            this.tabPageErrorLog = new System.Windows.Forms.TabPage();
            this.richTextBoxErrorTrace = new System.Windows.Forms.RichTextBox();
            this.tabPageTranslationHelper = new System.Windows.Forms.TabPage();
            this.splitContainerHelperPage = new System.Windows.Forms.SplitContainer();
            this.labelContextHint = new System.Windows.Forms.Label();
            this.buttonCommitChanges = new System.Windows.Forms.Button();
            this.buttonRefresh = new System.Windows.Forms.Button();
            this.dataGridViewUntranslated = new System.Windows.Forms.DataGridView();
            this.originalDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.translatedDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.languageDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.contextMenuStripLookup = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.untranslatedPairBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.groupBoxTranslationHelp = new System.Windows.Forms.GroupBox();
            this.dataGridViewFound = new System.Windows.Forms.DataGridView();
            this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.foundPairBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.textBoxSearch = new System.Windows.Forms.TextBox();
            this.labelSearch = new System.Windows.Forms.Label();
            //this.tabPageBrowser = new System.Windows.Forms.TabPage();
            //this.webBrowser = new System.Windows.Forms.WebBrowser();
            this.checkBoxTranslateNotes = new System.Windows.Forms.CheckBox();
            this.menuStrip = new System.Windows.Forms.MenuStrip();
            this.translateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripMenuItemAbout = new System.Windows.Forms.ToolStripMenuItem();
            this.textBoxSourcePath = new System.Windows.Forms.TextBox();
            this.translatedPairBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.statusStrip1.SuspendLayout();
            this.tabControl.SuspendLayout();
            this.tabPageFullLog.SuspendLayout();
            this.tabPageErrorLog.SuspendLayout();
            this.tabPageTranslationHelper.SuspendLayout();
            this.splitContainerHelperPage.Panel1.SuspendLayout();
            this.splitContainerHelperPage.Panel2.SuspendLayout();
            this.splitContainerHelperPage.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewUntranslated)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.untranslatedPairBindingSource)).BeginInit();
            this.groupBoxTranslationHelp.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewFound)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.foundPairBindingSource)).BeginInit();
            //this.tabPageBrowser.SuspendLayout();
            this.menuStrip.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.translatedPairBindingSource)).BeginInit();
            this.SuspendLayout();
            // 
            // buttonRun
            // 
            this.buttonRun.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonRun.Location = new System.Drawing.Point(754, 513);
            this.buttonRun.Name = "buttonRun";
            this.buttonRun.Size = new System.Drawing.Size(75, 23);
            this.buttonRun.TabIndex = 7;
            this.buttonRun.Text = "Run";
            this.buttonRun.UseVisualStyleBackColor = true;
            this.buttonRun.Click += new System.EventHandler(this.buttonRun_Click);
            // 
            // progressBar
            // 
            this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.progressBar.Location = new System.Drawing.Point(12, 455);
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(898, 23);
            this.progressBar.Step = 1;
            this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
            this.progressBar.TabIndex = 2;
            // 
            // buttonBrowse
            // 
            this.buttonBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonBrowse.Location = new System.Drawing.Point(835, 484);
            this.buttonBrowse.Name = "buttonBrowse";
            this.buttonBrowse.Size = new System.Drawing.Size(75, 23);
            this.buttonBrowse.TabIndex = 4;
            this.buttonBrowse.Text = "browse...";
            this.buttonBrowse.UseVisualStyleBackColor = true;
            this.buttonBrowse.Click += new System.EventHandler(this.buttonBrowse_Click);
            // 
            // openFileDialog
            // 
            this.openFileDialog.DefaultExt = "lua";
            this.openFileDialog.Filter = "lua Files|*.lua";
            this.openFileDialog.Multiselect = true;
            this.openFileDialog.RestoreDirectory = true;
            this.openFileDialog.Title = "Select TourGuide file";
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripStatusLabel});
            this.statusStrip1.Location = new System.Drawing.Point(0, 539);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(923, 22);
            this.statusStrip1.TabIndex = 6;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // toolStripStatusLabel
            // 
            this.toolStripStatusLabel.Name = "toolStripStatusLabel";
            this.toolStripStatusLabel.Size = new System.Drawing.Size(0, 17);
            // 
            // comboBoxTargetLanguage
            // 
            this.comboBoxTargetLanguage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.comboBoxTargetLanguage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBoxTargetLanguage.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.comboBoxTargetLanguage.FormattingEnabled = true;
            this.comboBoxTargetLanguage.Location = new System.Drawing.Point(118, 515);
            this.comboBoxTargetLanguage.Name = "comboBoxTargetLanguage";
            this.comboBoxTargetLanguage.Size = new System.Drawing.Size(406, 21);
            this.comboBoxTargetLanguage.TabIndex = 6;
            this.comboBoxTargetLanguage.SelectedIndexChanged += new System.EventHandler(this.comboBoxTargetLanguage_SelectedIndexChanged);
            // 
            // labelTargetLanguage
            // 
            this.labelTargetLanguage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.labelTargetLanguage.Location = new System.Drawing.Point(12, 515);
            this.labelTargetLanguage.Name = "labelTargetLanguage";
            this.labelTargetLanguage.Size = new System.Drawing.Size(100, 18);
            this.labelTargetLanguage.TabIndex = 5;
            this.labelTargetLanguage.Text = "target language";
            this.labelTargetLanguage.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // backgroundWorker
            // 
            this.backgroundWorker.WorkerReportsProgress = true;
            this.backgroundWorker.WorkerSupportsCancellation = true;
            this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
            this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
            this.backgroundWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker_ProgressChanged);
            // 
            // buttonCancel
            // 
            this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.buttonCancel.Location = new System.Drawing.Point(835, 513);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(75, 23);
            this.buttonCancel.TabIndex = 8;
            this.buttonCancel.Text = "Cancel";
            this.buttonCancel.UseVisualStyleBackColor = true;
            this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
            // 
            // richTextBoxTrace
            // 
            this.richTextBoxTrace.BackColor = System.Drawing.SystemColors.ControlLightLight;
            this.richTextBoxTrace.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBoxTrace.Location = new System.Drawing.Point(3, 3);
            this.richTextBoxTrace.Name = "richTextBoxTrace";
            this.richTextBoxTrace.ReadOnly = true;
            this.richTextBoxTrace.Size = new System.Drawing.Size(909, 390);
            this.richTextBoxTrace.TabIndex = 1;
            this.richTextBoxTrace.TabStop = false;
            this.richTextBoxTrace.Text = resources.GetString("richTextBoxTrace.Text");
            // 
            // tabControl
            // 
            this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tabControl.Controls.Add(this.tabPageFullLog);
            this.tabControl.Controls.Add(this.tabPageErrorLog);
            this.tabControl.Controls.Add(this.tabPageTranslationHelper);
            //this.tabControl.Controls.Add(this.tabPageBrowser);
            this.tabControl.Location = new System.Drawing.Point(0, 27);
            this.tabControl.Name = "tabControl";
            this.tabControl.SelectedIndex = 0;
            this.tabControl.Size = new System.Drawing.Size(923, 422);
            this.tabControl.TabIndex = 9;
            this.tabControl.Selected += new System.Windows.Forms.TabControlEventHandler(this.tabControl_Selected);
            // 
            // tabPageFullLog
            // 
            this.tabPageFullLog.Controls.Add(this.richTextBoxTrace);
            this.tabPageFullLog.Location = new System.Drawing.Point(4, 22);
            this.tabPageFullLog.Name = "tabPageFullLog";
            this.tabPageFullLog.Padding = new System.Windows.Forms.Padding(3);
            this.tabPageFullLog.Size = new System.Drawing.Size(915, 396);
            this.tabPageFullLog.TabIndex = 0;
            this.tabPageFullLog.Text = "Full log";
            this.tabPageFullLog.UseVisualStyleBackColor = true;
            // 
            // tabPageErrorLog
            // 
            this.tabPageErrorLog.Controls.Add(this.richTextBoxErrorTrace);
            this.tabPageErrorLog.Location = new System.Drawing.Point(4, 22);
            this.tabPageErrorLog.Name = "tabPageErrorLog";
            this.tabPageErrorLog.Padding = new System.Windows.Forms.Padding(3);
            this.tabPageErrorLog.Size = new System.Drawing.Size(915, 396);
            this.tabPageErrorLog.TabIndex = 1;
            this.tabPageErrorLog.Text = "Error log";
            this.tabPageErrorLog.UseVisualStyleBackColor = true;
            // 
            // richTextBoxErrorTrace
            // 
            this.richTextBoxErrorTrace.BackColor = System.Drawing.SystemColors.ControlLightLight;
            this.richTextBoxErrorTrace.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBoxErrorTrace.Location = new System.Drawing.Point(3, 3);
            this.richTextBoxErrorTrace.Name = "richTextBoxErrorTrace";
            this.richTextBoxErrorTrace.ReadOnly = true;
            this.richTextBoxErrorTrace.Size = new System.Drawing.Size(909, 390);
            this.richTextBoxErrorTrace.TabIndex = 2;
            this.richTextBoxErrorTrace.TabStop = false;
            this.richTextBoxErrorTrace.Text = "";
            // 
            // tabPageTranslationHelper
            // 
            this.tabPageTranslationHelper.Controls.Add(this.splitContainerHelperPage);
            this.tabPageTranslationHelper.Location = new System.Drawing.Point(4, 22);
            this.tabPageTranslationHelper.Name = "tabPageTranslationHelper";
            this.tabPageTranslationHelper.Padding = new System.Windows.Forms.Padding(3);
            this.tabPageTranslationHelper.Size = new System.Drawing.Size(915, 396);
            this.tabPageTranslationHelper.TabIndex = 2;
            this.tabPageTranslationHelper.Text = "Translation helper";
            this.tabPageTranslationHelper.UseVisualStyleBackColor = true;
            // 
            // splitContainerHelperPage
            // 
            this.splitContainerHelperPage.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainerHelperPage.Location = new System.Drawing.Point(3, 3);
            this.splitContainerHelperPage.Name = "splitContainerHelperPage";
            this.splitContainerHelperPage.Orientation = System.Windows.Forms.Orientation.Horizontal;
            // 
            // splitContainerHelperPage.Panel1
            // 
            this.splitContainerHelperPage.Panel1.Controls.Add(this.labelContextHint);
            this.splitContainerHelperPage.Panel1.Controls.Add(this.buttonCommitChanges);
            this.splitContainerHelperPage.Panel1.Controls.Add(this.buttonRefresh);
            this.splitContainerHelperPage.Panel1.Controls.Add(this.dataGridViewUntranslated);
            // 
            // splitContainerHelperPage.Panel2
            // 
            this.splitContainerHelperPage.Panel2.Controls.Add(this.groupBoxTranslationHelp);
            this.splitContainerHelperPage.Size = new System.Drawing.Size(909, 390);
            this.splitContainerHelperPage.SplitterDistance = 219;
            this.splitContainerHelperPage.TabIndex = 1;
            // 
            // labelContextHint
            // 
            this.labelContextHint.AutoSize = true;
            this.labelContextHint.Location = new System.Drawing.Point(213, 8);
            this.labelContextHint.Name = "labelContextHint";
            this.labelContextHint.Size = new System.Drawing.Size(302, 13);
            this.labelContextHint.TabIndex = 4;
            this.labelContextHint.Text = "Hint: right click on the grid to open the \"search\" context menu.";
            // 
            // buttonCommitChanges
            // 
            this.buttonCommitChanges.Location = new System.Drawing.Point(84, 3);
            this.buttonCommitChanges.Name = "buttonCommitChanges";
            this.buttonCommitChanges.Size = new System.Drawing.Size(123, 23);
            this.buttonCommitChanges.TabIndex = 3;
            this.buttonCommitChanges.Text = "Commit changes";
            this.buttonCommitChanges.UseVisualStyleBackColor = true;
            this.buttonCommitChanges.Click += new System.EventHandler(this.buttonCommitChanges_Click);
            // 
            // buttonRefresh
            // 
            this.buttonRefresh.Location = new System.Drawing.Point(3, 3);
            this.buttonRefresh.Name = "buttonRefresh";
            this.buttonRefresh.Size = new System.Drawing.Size(75, 23);
            this.buttonRefresh.TabIndex = 2;
            this.buttonRefresh.Text = "Refresh";
            this.buttonRefresh.UseVisualStyleBackColor = true;
            this.buttonRefresh.Click += new System.EventHandler(this.buttonRefresh_Click);
            // 
            // dataGridViewUntranslated
            // 
            this.dataGridViewUntranslated.AllowUserToAddRows = false;
            dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dataGridViewUntranslated.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
            this.dataGridViewUntranslated.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGridViewUntranslated.AutoGenerateColumns = false;
            this.dataGridViewUntranslated.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            this.dataGridViewUntranslated.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
            this.dataGridViewUntranslated.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridViewUntranslated.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.originalDataGridViewTextBoxColumn,
            this.translatedDataGridViewTextBoxColumn,
            this.languageDataGridViewTextBoxColumn});
            this.dataGridViewUntranslated.ContextMenuStrip = this.contextMenuStripLookup;
            this.dataGridViewUntranslated.DataSource = this.untranslatedPairBindingSource;
            dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window;
            dataGridViewCellStyle3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText;
            dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dataGridViewUntranslated.DefaultCellStyle = dataGridViewCellStyle3;
            this.dataGridViewUntranslated.Location = new System.Drawing.Point(3, 32);
            this.dataGridViewUntranslated.Name = "dataGridViewUntranslated";
            dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dataGridViewUntranslated.RowsDefaultCellStyle = dataGridViewCellStyle4;
            this.dataGridViewUntranslated.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dataGridViewUntranslated.Size = new System.Drawing.Size(903, 184);
            this.dataGridViewUntranslated.TabIndex = 0;
            this.dataGridViewUntranslated.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this.dataGridViewUntranslated_UserDeletingRow);
            this.dataGridViewUntranslated.UserDeletedRow += new System.Windows.Forms.DataGridViewRowEventHandler(this.dataGridViewUntranslated_UserDeletedRow);
            this.dataGridViewUntranslated.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewUntranslated_CellEndEdit);
            this.dataGridViewUntranslated.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.dataGridViewUntranslated_EditingControlShowing);
            // 
            // originalDataGridViewTextBoxColumn
            // 
            this.originalDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.originalDataGridViewTextBoxColumn.DataPropertyName = "Original";
            this.originalDataGridViewTextBoxColumn.HeaderText = "Original";
            this.originalDataGridViewTextBoxColumn.Name = "originalDataGridViewTextBoxColumn";
            // 
            // translatedDataGridViewTextBoxColumn
            // 
            this.translatedDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.translatedDataGridViewTextBoxColumn.DataPropertyName = "Translated";
            this.translatedDataGridViewTextBoxColumn.HeaderText = "Translated";
            this.translatedDataGridViewTextBoxColumn.Name = "translatedDataGridViewTextBoxColumn";
            // 
            // languageDataGridViewTextBoxColumn
            // 
            this.languageDataGridViewTextBoxColumn.DataPropertyName = "Language";
            this.languageDataGridViewTextBoxColumn.HeaderText = "Language";
            this.languageDataGridViewTextBoxColumn.Name = "languageDataGridViewTextBoxColumn";
            this.languageDataGridViewTextBoxColumn.Visible = false;
            // 
            // contextMenuStripLookup
            // 
            this.contextMenuStripLookup.Name = "contextMenuStripLookup";
            this.contextMenuStripLookup.Size = new System.Drawing.Size(61, 4);
            // 
            // untranslatedPairBindingSource
            // 
            this.untranslatedPairBindingSource.AllowNew = false;
            this.untranslatedPairBindingSource.DataSource = typeof(WowTourGuideTranslator.TranslatedPair);
            // 
            // groupBoxTranslationHelp
            // 
            this.groupBoxTranslationHelp.Controls.Add(this.dataGridViewFound);
            this.groupBoxTranslationHelp.Controls.Add(this.textBoxSearch);
            this.groupBoxTranslationHelp.Controls.Add(this.labelSearch);
            this.groupBoxTranslationHelp.Dock = System.Windows.Forms.DockStyle.Fill;
            this.groupBoxTranslationHelp.Location = new System.Drawing.Point(0, 0);
            this.groupBoxTranslationHelp.Name = "groupBoxTranslationHelp";
            this.groupBoxTranslationHelp.Size = new System.Drawing.Size(909, 167);
            this.groupBoxTranslationHelp.TabIndex = 0;
            this.groupBoxTranslationHelp.TabStop = false;
            this.groupBoxTranslationHelp.Text = "Translation search";
            // 
            // dataGridViewFound
            // 
            this.dataGridViewFound.AllowUserToAddRows = false;
            dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dataGridViewFound.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle5;
            this.dataGridViewFound.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGridViewFound.AutoGenerateColumns = false;
            this.dataGridViewFound.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
            this.dataGridViewFound.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridViewFound.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.dataGridViewTextBoxColumn4,
            this.dataGridViewTextBoxColumn5,
            this.dataGridViewTextBoxColumn6});
            this.dataGridViewFound.DataSource = this.foundPairBindingSource;
            dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle6.BackColor = System.Drawing.SystemColors.Window;
            dataGridViewCellStyle6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle6.ForeColor = System.Drawing.SystemColors.ControlText;
            dataGridViewCellStyle6.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle6.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle6.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dataGridViewFound.DefaultCellStyle = dataGridViewCellStyle6;
            this.dataGridViewFound.Location = new System.Drawing.Point(6, 39);
            this.dataGridViewFound.Name = "dataGridViewFound";
            this.dataGridViewFound.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dataGridViewFound.Size = new System.Drawing.Size(897, 122);
            this.dataGridViewFound.TabIndex = 2;
            this.dataGridViewFound.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewFound_CellEndEdit);
            // 
            // dataGridViewTextBoxColumn4
            // 
            this.dataGridViewTextBoxColumn4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.dataGridViewTextBoxColumn4.DataPropertyName = "Original";
            this.dataGridViewTextBoxColumn4.HeaderText = "Original";
            this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
            this.dataGridViewTextBoxColumn4.ReadOnly = true;
            this.dataGridViewTextBoxColumn4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic;
            // 
            // dataGridViewTextBoxColumn5
            // 
            this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.dataGridViewTextBoxColumn5.DataPropertyName = "Translated";
            this.dataGridViewTextBoxColumn5.HeaderText = "Translated";
            this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5";
            // 
            // dataGridViewTextBoxColumn6
            // 
            this.dataGridViewTextBoxColumn6.DataPropertyName = "Language";
            this.dataGridViewTextBoxColumn6.HeaderText = "Language";
            this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6";
            this.dataGridViewTextBoxColumn6.Visible = false;
            // 
            // foundPairBindingSource
            // 
            this.foundPairBindingSource.DataSource = typeof(WowTourGuideTranslator.TranslatedPair);
            // 
            // textBoxSearch
            // 
            this.textBoxSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.textBoxSearch.Location = new System.Drawing.Point(51, 13);
            this.textBoxSearch.Name = "textBoxSearch";
            this.textBoxSearch.Size = new System.Drawing.Size(852, 20);
            this.textBoxSearch.TabIndex = 1;
            this.textBoxSearch.TextChanged += new System.EventHandler(this.textBoxSearch_TextChanged);
            // 
            // labelSearch
            // 
            this.labelSearch.AutoSize = true;
            this.labelSearch.Location = new System.Drawing.Point(6, 16);
            this.labelSearch.Name = "labelSearch";
            this.labelSearch.Size = new System.Drawing.Size(39, 13);
            this.labelSearch.TabIndex = 0;
            this.labelSearch.Text = "search";
            // 
            // tabPageBrowser
            // 
            //this.tabPageBrowser.Controls.Add(this.webBrowser);
            //this.tabPageBrowser.Location = new System.Drawing.Point(4, 22);
            //this.tabPageBrowser.Name = "tabPageBrowser";
            //this.tabPageBrowser.Padding = new System.Windows.Forms.Padding(3);
            //this.tabPageBrowser.Size = new System.Drawing.Size(915, 396);
            //this.tabPageBrowser.TabIndex = 3;
            //this.tabPageBrowser.Text = "Browser";
            //this.tabPageBrowser.UseVisualStyleBackColor = true;
            // 
            // webBrowser
            // 
            //this.webBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.webBrowser.Location = new System.Drawing.Point(3, 3);
            //this.webBrowser.MinimumSize = new System.Drawing.Size(20, 20);
            //this.webBrowser.Name = "webBrowser";
            //this.webBrowser.Size = new System.Drawing.Size(909, 390);
            //this.webBrowser.TabIndex = 0;
            //this.webBrowser.Url = new System.Uri("http://www.wowhead.com/", System.UriKind.Absolute);
            // 
            // checkBoxTranslateNotes
            // 
            this.checkBoxTranslateNotes.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.checkBoxTranslateNotes.AutoSize = true;
            this.checkBoxTranslateNotes.Location = new System.Drawing.Point(554, 517);
            this.checkBoxTranslateNotes.Name = "checkBoxTranslateNotes";
            this.checkBoxTranslateNotes.Size = new System.Drawing.Size(121, 17);
            this.checkBoxTranslateNotes.TabIndex = 10;
            this.checkBoxTranslateNotes.Text = "try to translate notes";
            this.checkBoxTranslateNotes.UseVisualStyleBackColor = true;
            this.checkBoxTranslateNotes.CheckedChanged += new System.EventHandler(this.checkBoxTranslateNotes_CheckedChanged);
            // 
            // menuStrip
            // 
            this.menuStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
            this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.translateToolStripMenuItem,
            this.toolStripMenuItemAbout,
            this.clearToolStripMenuItem});
            this.menuStrip.Location = new System.Drawing.Point(0, 0);
            this.menuStrip.Name = "menuStrip";
            this.menuStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
            this.menuStrip.Size = new System.Drawing.Size(923, 24);
            this.menuStrip.TabIndex = 11;
            this.menuStrip.Text = "menuStrip";
            // 
            // translateToolStripMenuItem
            // 
            this.translateToolStripMenuItem.Name = "translateToolStripMenuItem";
            this.translateToolStripMenuItem.ShortcutKeyDisplayString = "F5";
            this.translateToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5;
            this.translateToolStripMenuItem.Size = new System.Drawing.Size(87, 20);
            this.translateToolStripMenuItem.Text = "Translate (F5)";
            this.translateToolStripMenuItem.Click += new System.EventHandler(this.translateToolStripMenuItem_Click);
            // 
            // toolStripMenuItemAbout
            // 
            this.toolStripMenuItemAbout.Name = "toolStripMenuItemAbout";
            this.toolStripMenuItemAbout.Size = new System.Drawing.Size(48, 20);
            this.toolStripMenuItemAbout.Text = "About";
            this.toolStripMenuItemAbout.Click += new System.EventHandler(this.toolStripMenuItemAbout_Click);
            // 
            // textBoxSourcePath
            // 
            this.textBoxSourcePath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.textBoxSourcePath.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
            this.textBoxSourcePath.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem;
            this.textBoxSourcePath.Location = new System.Drawing.Point(12, 486);
            this.textBoxSourcePath.Name = "textBoxSourcePath";
            this.textBoxSourcePath.Size = new System.Drawing.Size(817, 20);
            this.textBoxSourcePath.TabIndex = 3;
            // 
            // translatedPairBindingSource
            // 
            this.translatedPairBindingSource.DataSource = typeof(WowTourGuideTranslator.TranslatedPair);
            // 
            // clearToolStripMenuItem
            // 
            this.clearToolStripMenuItem.Name = "clearToolStripMenuItem";
            this.clearToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
            this.clearToolStripMenuItem.Text = "Clear";
            this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click);
            // 
            // TourGuideBaseTranslatorForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(923, 561);
            this.Controls.Add(this.checkBoxTranslateNotes);
            this.Controls.Add(this.tabControl);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.labelTargetLanguage);
            this.Controls.Add(this.comboBoxTargetLanguage);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.menuStrip);
            this.Controls.Add(this.buttonBrowse);
            this.Controls.Add(this.textBoxSourcePath);
            this.Controls.Add(this.progressBar);
            this.Controls.Add(this.buttonRun);
            this.MainMenuStrip = this.menuStrip;
            this.Name = "TourGuideBaseTranslatorForm";
            this.Text = "WowTourGuideTranslator";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.TourGuideBaseTranslatorForm_FormClosed);
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.tabControl.ResumeLayout(false);
            this.tabPageFullLog.ResumeLayout(false);
            this.tabPageErrorLog.ResumeLayout(false);
            this.tabPageTranslationHelper.ResumeLayout(false);
            this.splitContainerHelperPage.Panel1.ResumeLayout(false);
            this.splitContainerHelperPage.Panel1.PerformLayout();
            this.splitContainerHelperPage.Panel2.ResumeLayout(false);
            this.splitContainerHelperPage.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewUntranslated)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.untranslatedPairBindingSource)).EndInit();
            this.groupBoxTranslationHelp.ResumeLayout(false);
            this.groupBoxTranslationHelp.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewFound)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.foundPairBindingSource)).EndInit();
            //this.tabPageBrowser.ResumeLayout(false);
            this.menuStrip.ResumeLayout(false);
            this.menuStrip.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.translatedPairBindingSource)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        /// <summary>
        /// Handles the Click event of the buttonBrowse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                this.textBoxSourcePath.Clear();
                StringBuilder builder = new StringBuilder();

                foreach (string path in this.openFileDialog.FileNames)
                {
                    if (builder.Length > 0)
                    {
                        builder.Append(@";");
                    }

                    builder.Append(path);
                }

                this.textBoxSourcePath.Text = builder.ToString();
            }
        }

        /// <summary>
        /// Handles the Click event of the buttonRun control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonRun_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBoxSourcePath.Text))
            {
                MessageBox.Show("Please enter a valid guide path!");
                return;
            }

            string[] paths = this.textBoxSourcePath.Text.Split(';');

            if (paths.Any((path) => !File.Exists(path)))
            {
                MessageBox.Show("A File in your list doesn't exist!");
                return;
            }

            this.backgroundWorker.RunWorkerAsync();
            this.buttonRun.Enabled = false;
        }

        /// <summary>
        /// Handles the Click event of the buttonCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (this.backgroundWorker.IsBusy)
            {
                this.backgroundWorker.CancelAsync();
            }
            else
            {
                this.Close();
            }
        }
        
        /// <summary>
        /// Handles the DoWork event of the backgroundWorker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // get guide paths
                string[] paths = this.textBoxSourcePath.Text.Split(';');

                // for all guide paths
                foreach (string path in paths)
                {
                    Trace(@"Translating guide in file ""{0}""...", path);

                    TranslateGuide(path);
                }
            }
            catch (TourGuideCancelationException)
            {
                Warn("Translation process canceled by user!");
            }
            catch (Exception ex)
            {
                this.Error(ex.ToString());
            }
        }

        /// <summary>
        /// Translates the guide.
        /// </summary>
        /// <param name="path">The path.</param>
        private void TranslateGuide(string path)
        {
            TourGuideTranslator translator = new TourGuideTranslator(path, DataProvider.DataLanguage);

            translator.TranslateGuide();
        }


        /// <summary>
        /// Gets the selected language string.
        /// </summary>
        /// <returns></returns>
        private string GetLang()
        {
            if (this.InvokeRequired)
            {
                return (string)this.Invoke(new Func<string>(GetLang));
            }
            else
            {
                return this.comboBoxTargetLanguage.SelectedItem.ToString();
            }
        }

        /// <summary>
        /// Handles the ProgressChanged event of the backgroundWorker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.ProgressChangedEventArgs"/> instance containing the event data.</param>
        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar.Value = e.ProgressPercentage;

            string message = e.UserState as string;
            if (message != null)
            {
                this.Trace(message);
            }
        }

        /// <summary>
        /// Handles the RunWorkerCompleted event of the backgroundWorker control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Trace("Completed!");
            this.buttonRun.Enabled = true;
        }

        /// <summary>
        /// Traces the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Trace(string message, params object[] values)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, object[]>(Trace), message, values);
            }
            else
            {
                Color dispColor = Color.Black;
                AppendToTraceBox(message, values, dispColor, false);
            }
        }

        /// <summary>
        /// Traces the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Warn(string message, params object[] values)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, object[]>(Warn), message, values);
            }
            else
            {
                Color dispColor = Color.Orange;
                AppendToTraceBox(message, values, dispColor, true);
            }
        }

        /// <summary>
        /// Traces the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void TranslationFailed(string message, params object[] values)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, object[]>(TranslationFailed), message, values);
            }
            else
            {
                Color dispColor = Color.Green;
                AppendToTraceBox(message, values, dispColor, true);
            }
        }

        /// <summary>
        /// Traces the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Error(string message, params object[] values)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, object[]>(Error), message, values);
            }
            else
            {
                Color dispColor = Color.Red;
                AppendToTraceBox(message, values, dispColor, true);
            }
        }

        /// <summary>
        /// Appends to trace box.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="values">The values.</param>
        /// <param name="dispColor">Color of the disp.</param>
        /// <param name="isError">if set to <c>true</c> [is error].</param>
        private void AppendToTraceBox(string message, object[] values, Color dispColor, bool isError)
        {
            string warning = string.Format(message, values) + "\n";
            AppendToBox(dispColor, warning, this.richTextBoxTrace);
            if (isError)
                AppendToBox(dispColor, warning, this.richTextBoxErrorTrace);
            System.Diagnostics.Trace.WriteLine(string.Format(message, values));
            this.toolStripStatusLabel.Text = string.Format(message, values);
        }

        /// <summary>
        /// Appends to box.
        /// </summary>
        /// <param name="dispColor">Color of the text to append.</param>
        /// <param name="warning">The warning text.</param>
        /// <param name="box">The box.</param>
        private void AppendToBox(Color dispColor, string warning, RichTextBox box)
        {
            int baseLength = box.Text.Length;
            Color oldColor = box.SelectionColor;
            box.AppendText(warning);
            if (oldColor != dispColor)
            {
                box.Select(baseLength, box.Text.Length - baseLength);
                box.SelectionColor = dispColor;
            }
            box.Select(this.richTextBoxTrace.Text.Length - 1, 0);
            box.SelectionColor = oldColor;
            box.ScrollToCaret();
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the comboBoxTargetLanguage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void comboBoxTargetLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            // change the language
            DataProvider.DataLanguage = this.GetLang();
            this.RefreshTranslatedGridView();
            this.RefreshUntranslatedDataGridView();
        }

        /// <summary>
        /// Handles the FormClosed event of the TourGuideBaseTranslatorForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosedEventArgs"/> instance containing the event data.</param>
        private void TourGuideBaseTranslatorForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            DataProvider.PersistData();
        }

        /// <summary>
        /// Handles the CheckedChanged event of the checkBoxTranslateNotes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void checkBoxTranslateNotes_CheckedChanged(object sender, EventArgs e)
        {
            DataProvider.TranslateNotes = this.checkBoxTranslateNotes.Checked;
        }

        /// <summary>
        /// Handles the TextChanged event of the textBoxSearch control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void textBoxSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshTranslatedGridView();
        }

        /// <summary>
        /// Handles the CellEndEdit event of the dataGridViewFound control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellEventArgs"/> instance containing the event data.</param>
        private void dataGridViewFound_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // save changes from the dataGridView in the TranslationsDict
            TranslatedPair changedPair = (TranslatedPair)this.foundPairBindingSource[e.RowIndex];

            DataProvider.TranslationsDict[changedPair.Original] = changedPair.Translated;
        }

        /// <summary>
        /// Handles the Selected event of the tabControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.TabControlEventArgs"/> instance containing the event data.</param>
        private void tabControl_Selected(object sender, TabControlEventArgs e)
        {
            // if transaltion help tab page register Events
            if (e.TabPageIndex == 2 && !this.dataGridViewUntranslatedDirty)
            {
                RefreshUntranslatedDataGridView();
            }
        }


        /// <summary>
        /// Handles the Click event of the buttonRefresh control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            if (this.dataGridViewUntranslatedDirty)
            {
                string msg = "Do you really want to refresh?\nAll uncommitted changes will be lost!";
                DialogResult result = MessageBox.Show(this, msg, "Really refresh?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                if (result == DialogResult.Yes)
                {
                    RefreshUntranslatedDataGridView();
                    RefreshTranslatedGridView();
                }
            }
            else
            {
                RefreshUntranslatedDataGridView();
                RefreshTranslatedGridView();
            }
        }

        /// <summary>
        /// Handles the Click event of the buttonCommitChanges control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonCommitChanges_Click(object sender, EventArgs e)
        {
            IEnumerable<TranslatedPair> pairEnum = from TranslatedPair transPair in this.untranslatedPairBindingSource
                                                   where !string.IsNullOrEmpty(transPair.Translated)
                                                   select transPair;

            // add all newly translated texts to the TranslationsDict
            foreach (TranslatedPair pair in pairEnum)
            {
                if (!DataProvider.TranslationsDict.ContainsKey(pair.Original))
                {
                    DataProvider.TranslationsDict.Add(pair.Original, pair.Translated);
                    DataProvider.UntranslatedDict.Remove(pair.Original);
                }
                else
                {
                    string msg = string.Format("The text \"{0}\" already exists in the translations with the translation \"{1}\"!\n" +
                        "Do you want to overwrite it with \"{0}\"/\"{2}\"?",
                        pair.Original, pair.Translated, DataProvider.TranslationsDict[pair.Original]);
                    DialogResult result =  MessageBox.Show(this, msg, "Overwrite translation?", MessageBoxButtons.YesNo);

                    if (result == DialogResult.Yes)
                    {
                        DataProvider.TranslationsDict[pair.Original] = pair.Translated;
                        DataProvider.UntranslatedDict.Remove(pair.Original);
                    }
                }
            }

            RefreshUntranslatedDataGridView();
            RefreshTranslatedGridView();
            DataProvider.PersistData();
        }

        /// <summary>
        /// Refreshes the translated grid view.
        /// </summary>
        private void RefreshTranslatedGridView()
        {
            // handle each changed char and display only relevant data
            var data = from pair in DataProvider.TranslationsDict
                       where pair.Key.IndexOf(this.textBoxSearch.Text, StringComparison.CurrentCultureIgnoreCase)  >= 0
                       select new TranslatedPair()
                       {
                           Language = DataProvider.DataLanguage,
                           Original = pair.Key,
                           Translated = pair.Value
                       };

            this.foundPairBindingSource.DataSource = new BindingList<TranslatedPair>(data.ToArray());
        }

        /// <summary>
        /// Refreshes the untranslated data grid view.
        /// </summary>
        private void RefreshUntranslatedDataGridView()
        {
            // handle display untranslated data
            var data = from pair in DataProvider.UntranslatedDict
                       select new TranslatedPair()
                       {
                           Language = DataProvider.DataLanguage,
                           Original = pair.Key,
                           Translated = pair.Value
                       };

            BindingList<TranslatedPair> bindingList = new BindingList<TranslatedPair>();
            bindingList.AllowRemove = true;
            foreach (TranslatedPair pair in data)
            {
                bindingList.Add(pair);
            }

            this.untranslatedPairBindingSource.DataSource = bindingList;
            this.dataGridViewUntranslatedDirty = false;
        }

        /// <summary>
        /// Handles the Click event of the buttonSearchWowhead control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonSearchWowhead_Click(object sender, EventArgs e)
        {
            string searchUrlBase = @"http://www.wowhead.com/?search={0}";
            DataGridViewTextBoxCell currentCell = dataGridViewUntranslated.CurrentCell as DataGridViewTextBoxCell;
            string searchText = string.Empty;

            if (currentCell != null)
            {
                TextBox box = dataGridViewUntranslated.EditingControl as TextBox;

                if (box != null)
                {
                    if (box.SelectionLength > 0)
                    {
                        searchText = box.SelectedText;
                    }
                    else
                    {
                        searchText = box.Text;
                    }
                }
                else
                {
                    searchText = (string)currentCell.Value;
                }

                string url = Uri.EscapeDataString(string.Format(searchUrlBase, searchText));

                if (!Program.RunsOnMono)
                {
                    this.webBrowser.Navigate(url);
                    this.tabControl.SelectedTab = this.tabPageBrowser;
                }
                else
                {
                    Process.Start(url);
                }
            }
            else
            {
                MessageBox.Show("Nothing selected!");
            }
        }

        /// <summary>
        /// Translates the selected text with URL.
        /// </summary>
        /// <param name="searchUrlBase">The search URL base.</param>
        /// <remarks>The URL must contain a {0} placeholder for the search string</remarks>
        private void TranslateSelectedTextWithUrl(string searchUrlBase)
        {
            DataGridViewTextBoxCell currentCell = dataGridViewUntranslated.CurrentCell as DataGridViewTextBoxCell;
            string searchText = string.Empty;

            if (currentCell != null)
            {
                TextBox box = dataGridViewUntranslated.EditingControl as TextBox;

                if (box != null)
                {
                    if (box.SelectionLength > 0)
                    {
                        searchText = box.SelectedText;
                    }
                    else
                    {
                        searchText = box.Text;
                    }
                }
                else
                {
                    searchText = (string)currentCell.Value;
                }

                string url = string.Format(searchUrlBase, Uri.EscapeDataString(searchText));


                if (!Program.RunsOnMono)
                {
                    this.webBrowser.Navigate(url);
                    this.tabControl.SelectedTab = this.tabPageBrowser;
                }
                else
                {
                    Process.Start(url);
                }
            }
            else
            {
                MessageBox.Show("Nothing selected!");
            }
        }

        /// <summary>
        /// Handles the Click event of the contextMenuLookup MenuItems controls.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void contextMenuLookupsItem_Click(object sender, EventArgs e)
        {
            // get the clicked item
            MenuItem item = sender as MenuItem;

            if (item != null)
            {
                // get the atached search url for the item
                string searchUrl = item.Tag as string;

                if (! string.IsNullOrEmpty(searchUrl))
                {
                    // open the translation
                    TranslateSelectedTextWithUrl(searchUrl);
                }

                return;
            }

            ToolStripMenuItem stripItem = sender as ToolStripMenuItem;

            if (stripItem != null)
            {
                // get the atached search url for the item
                string searchUrl = stripItem.Tag as string;

                if (! string.IsNullOrEmpty(searchUrl))
                {
                    // open the translation
                    TranslateSelectedTextWithUrl(searchUrl);
                }

                return;
            }


            
        }

        /// <summary>
        /// Handles the EditingControlShowing event of the dataGridViewUntranslated control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewEditingControlShowingEventArgs"/> instance containing the event data.</param>
        private void dataGridViewUntranslated_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            TextBox box = e.Control as TextBox;

            if (box != null)
            {
                box.ContextMenu = this.contextMenuLookups;
                box.Multiline = true;
                box.WordWrap = true;
            }
        }

        /// <summary>
        /// Handles the CellEndEdit event of the dataGridViewUntranslated control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellEventArgs"/> instance containing the event data.</param>
        private void dataGridViewUntranslated_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // register changes
            if (!string.IsNullOrEmpty((string)dataGridViewUntranslated[e.ColumnIndex, e.RowIndex].Value))
            {
                this.dataGridViewUntranslatedDirty = true;
            }
        }

        /// <summary>
        /// Handles the UserDeletedRow event of the dataGridViewUntranslated control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewRowEventArgs"/> instance containing the event data.</param>
        private void dataGridViewUntranslated_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
        }

        private void dataGridViewUntranslated_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            TranslatedPair pair = e.Row.DataBoundItem as TranslatedPair;

            if (pair != null)
            {
                // remove from the dictionary of untranslated texts
                DataProvider.UntranslatedDict.Remove(pair.Original);
            }
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItemAbout control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItemAbout_Click(object sender, EventArgs e)
        {
            AboutBox aboutBox = new AboutBox();

            aboutBox.ShowDialog(this);
        }

        private void translateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tabControl.SelectedTab == this.tabPageTranslationHelper)
                {
                    DataGridViewTextBoxCell currentCell = dataGridViewUntranslated.CurrentCell as DataGridViewTextBoxCell;
                    string searchText = string.Empty;

                    if (currentCell != null)
                    {
                        TextBox box = dataGridViewUntranslated.EditingControl as TextBox;

                        if (box != null)
                        {
                            if (box.SelectionLength > 0)
                            {
                                searchText = box.SelectedText;
                            }
                            else
                            {
                                searchText = box.Text;
                            }
                        }
                        else
                        {
                            searchText = (string)currentCell.Value;
                        }

                        if (string.IsNullOrEmpty(searchText))
                        {
                            return;
                        }

                    string translatedText = Translator.Translate(searchText, Gapi.Language.Language.English, DataProvider.GapiLanguage);

                        // target column
                        if (currentCell.ColumnIndex == this.translatedDataGridViewTextBoxColumn.Index)
                        {
                            if (box != null)
                            {
                                if (box.SelectionLength > 0)
                                {
                                    box.SelectedText = translatedText; ;
                                }
                                else
                                {
                                    box.Text = translatedText;
                                }
                            }
                            else
                            {
                                currentCell.Value = translatedText; ;
                            }
                        }
                        // source column
                        else
                        {
                            DataGridViewTextBoxCell targetCell = this.dataGridViewUntranslated[this.translatedDataGridViewTextBoxColumn.Index, currentCell.RowIndex] as DataGridViewTextBoxCell;

                            if (targetCell != null)
                            {
                                targetCell.Value = translatedText;
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Nothing selected!");
                    }
                }
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled)
                    log.Error("Error while translating text!", ex);
                MessageBox.Show(string.Format("Error while translating text!\n{0}", ex));
            }
        }

        /// <summary>
        /// Handles the Click event of the clearToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.richTextBoxTrace.Clear();
            this.richTextBoxErrorTrace.Clear();
        }

  
    }
}
